#!/bin/bash

export TINY_WEB_ROOT_DIR="$(pwd)"
echo "TINY_WEB_ROOT_DIR = $TINY_WEB_ROOT_DIR"

# Setup Node.js environment
prebuild() {
    echo "Setting up Node.js environment..."
    
    # Check if tools directory exists
    if [ ! -d "prebuild" ]; then
        echo "Creating prebuild directory..."
        mkdir prebuild
    fi

    if [ ! -d "prebuild/node-v22.17.1-linux-x64" ]; then
        # Download Node.js if not already downloaded
        if [ ! -f "tools/node-v22.17.1-linux-x64.tar.xz" ]; then
            echo "Downloading Node.js..."
            wget -q https://nodejs.org/dist/v22.17.1/node-v22.17.1-linux-x64.tar.xz -P tools/
        fi
        echo "Extracting Node.js..."
        tar -xf tools/node-v22.17.1-linux-x64.tar.xz -C prebuild/
    else
        echo "Node.js already extracted..."
    fi
}

# Default pack (uses original output location)
pack() {
    echo "Packing to default location..."
}

build_webserver() {
    echo "Building webserver..."
    cd webserver/
    mkdir -p build
    cd build
    cmake ..
    make

    echo "Web server built!"
    cd $TINY_WEB_ROOT_DIR
}

clean_webserver() {
    rm -rf ./webserver/build
    echo "webserver Cleanup completed"
}

build() {
    echo "Building..."
    build_webserver
}

clean() {
    clean_webserver
    echo "Cleanup completed"
}

if [ ! -d "prebuild/node-v22.17.1-linux-x64" ]; then
    echo "ERROR:Node.js environment not set up. Running prebuild..."
fi

# Display help information
help() {
    echo "Available commands:"
    echo ""
    echo "  prebuild       - Set up Node.js environment (download and extract if needed)"
    echo "  build          - Build project"
    echo "  build-webserver - Build webserver (only)"
    echo "  pack           - Pack both release and debug versions (default)"
    echo "  help           - Show this help message"
    echo ""
    echo "Environment:"
    echo "  Node.js binaries are added to PATH automatically"
}

export PATH="$PATH:$(pwd)/prebuild/node-v22.17.1-linux-x64/bin"

# Show help if script is called without arguments
if [ $# -eq 0 ]; then
    help
fi